<?php
namespace Addons\Calendar\Controller;
use Home\Controller\AddonsController;

require_once( dirname(__FILE__) . "/SolarLunarController.class.php");

class CalendarController extends AddonsController{
	// 获取节日，传值进去的是一个内容数组
	private function _get_fetv($options) {
		if(!$options)
			return false;
	
		if(isset($options['uid']))
			$base['uid'] = $options['uid'];
			
		if(isset($options['remind_set'])) {
			$base['remind_set'] = $options['remind_set'];
			$base['remind_set_time'] = $options['remind_set_time'];
		}
		
		$base['date_format'] = '0';
		
		// 取公历周年纪念日
		$ftmp = M ( 'calendar_remind_info' )->where ($base) 
			->where(Array('recycle'=>'1', 'remind_month'=>@$options['month'], 'remind_day'=>@$options['day']))
			->getFields ( 'remind_title,id' );	// id 用来跳转和编辑
		$fetv = empty($ftmp) ? Array() : $ftmp;
		
		// 取公历月度纪念日
		$ftmp = M ( 'calendar_remind_info' )->where ($base)
			->where(Array('recycle'=>'2', 'remind_day'=>@$options['day']))
			->getFields ( 'remind_title,id' );	// id 用来跳转和编辑
		$fetv = empty($ftmp) ? $fetv : $fetv+$ftmp;
		
		// 取公历单次提醒
		$ftmp = M ( 'calendar_remind_info' )->where ($base) 
			->where(Array('recycle'=>'3', 'remind_month'=>@$options['month'], 'remind_day'=>@$options['day'], 'remind_year'=>@$options['year'])) 
			->getFields ( 'remind_title,id' );	// id 用来跳转和编辑
		$fetv = empty($ftmp) ? $fetv : $fetv+$ftmp;
		
		$base['date_format'] = '1';	// 取农历节日
		
		// 取农历周年纪念日
		$ftmp = M ( 'calendar_remind_info' )->where ($base) 
			->where(Array('recycle'=>'1', 'remind_month'=>@$options['lunar_month'], 'remind_day'=>@$options['lunar_day'])) 
			->getFields ( 'remind_title,id' );	// id 用来跳转和编辑
		$fetv = empty($ftmp) ? $fetv : $fetv+$ftmp;
		
		// 取农历月度纪念日
		$ftmp = M ( 'calendar_remind_info' )->where ($base) 
			->where(Array('recycle'=>'2', 'remind_day'=>@$options['lunar_day'])) 
			->getFields ( 'remind_title,id' );	// id 用来跳转和编辑
		$fetv = empty($ftmp) ? $fetv : $fetv+$ftmp;
		
		// 取农历单次提醒
		$ftmp = M ( 'calendar_remind_info' )->where ($base) 
			->where(Array('recycle'=>'3', 'remind_month'=>@$options['lunar_month'], 'remind_day'=>@$options['lunar_day'], 'remind_year'=>@$options['lunar_year'])) 
			->getFields ( 'remind_title,id' );	// id 用来跳转和编辑
		$fetv = empty($ftmp) ? $fetv : $fetv+$ftmp;
	
		return $fetv;
	}
	
	/* 根据公历获取年历，并填充到数组 ahead_days 表示提前多久 */
	private function _getDays($ahead_days) {
		if($ahead_days < 0) {
			return false;
		} else if($ahead_days == 1) {
			$days = date("Y-m-d", strtotime("+1 day"));
		} else if($ahead_days == 7) {
			$days = date("Y-m-d", strtotime("+1 week"));
		} else {
			$days = date("Y-m-d");
		}
	
		$days = explode('-', $days);

		//$out = json_decode(outputCurl("http://api.tuijs.com/solarToLunar?year=". $days[0] . "&month=" . $days[1] . "&day=" . $days[2]), true);
		
		$solar = new Solar();
		$solar->solarYear = $days[0];
		$solar->solarMonth = $days[1];
		$solar->solarDay = $days[2];
		
		$lunar = SolarLunarController::_solar_to_lunar($solar);		
		if(!$lunar) {
			return false;
		}
		
		$out['lunar_year'] = $lunar->lunarYear;
		$out['lunar_month'] = $lunar->lunarMonth;
		$out['lunar_day'] = $lunar->lunarDay;
		
		$out['year'] = $days[0];
		$out['month'] = $days[1];
		$out['day'] = $days[2];
		
		$out['remind_set'] = $ahead_days;
		$out['remind_set_time'] = date('H');
		
		return $out;
	}
	
	/* 获取提前多久的节日 */
	private function _get_fetv_by_options($options) {
		// 当天提醒的
		$ftmp = $this->_get_fetv($this->_getDays(0));
		$fetv = empty($ftmp) ? Array() : $ftmp;
		
		// 提前1天提醒
		$ftmp = $this->_get_fetv($this->_getDays(1));
		$fetv = empty($ftmp) ? $fetv : $fetv+$ftmp;
		
		// 提前7天提醒
		$ftmp = $this->_get_fetv($this->_getDays(7));
		$fetv = empty($ftmp) ? $fetv : $fetv+$ftmp;
		
		return $fetv;
	}
	
	/* 发送模板消息 */
	function _replyData($uid, $param,$template_id,$jumpUrl='') {
		if($uid < 0) {
			return false;	// uid 不合法
		}
		$map ['token'] = get_token ();
		$map ['uid'] = $uid;
		$param ['touser'] = M ( 'public_follow' )->where ( $map )->getField ( 'openid' );
        $param['template_id']=$template_id;
        $param['url']=$jumpUrl;
		
		$url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . get_access_token ();

		$result ['status'] = 0;
		$res = post_data ( $url, $param );
		
		//file_put_contents("./csz3.txt", "url=" . serialize($url) . ", \nparam=" . serialize($param) . "\n", FILE_APPEND);
		
		if ($res ['errcode'] != 0) {
			$result ['msg'] = error_msg ($res);
		} else {
			$result ['status'] = 1;
			$result ['msg'] = '发送成功';
		}
		return $result;
	}
	
	// 执行发送消息，每次请求都会造成发送一次模板消息，因此要加密判断
	public function send_template_remind() {
		$curtime = time();
		$last = S('template_send');
		
		/*
		if($last && ($curtime-$last)<60*10) {	// 间隔不到10min, 不发送
			file_put_contents("./attack.txt", "attack in send_template_remind, freq send!\ncurtime=" . $curtime . ", lasttime=" . $last . ", request is: " . serialize($_REQUEST) . "\n", FILE_APPEND);
			return false;
		}
		*/
		
		S('template_send', $curtime);
		unset($_REQUEST['uid']);
		
		$encode = "goomtu_template_remind";
		
		if($_REQUEST['encode'] != $encode) {
			file_put_contents("./attack.txt", "attack in send_template_remind, code is wrong!\nrequest is: " . serialize($_REQUEST) . "\n", FILE_APPEND);
			return false;
		}
		
		// 根据不同设置，获取节日，分为当天提醒、提前一天提醒、提前七天提醒
		$fetv = $this->_get_fetv_by_options($_REQUEST);
		
		file_put_contents("./csz3.txt", "fetv=" . serialize($fetv) . ", \n_REQUEST=" . serialize($_REQUEST) . "\n", FILE_APPEND);
		
		/**
		 * template:
节日提醒
你好， {{remind_ahead.DATA}} 你将有一个节日来临。 

节日名称：{{remind_title.DATA}} 
节日日期：{{remind_time.DATA}} 
节日类型：{{remind_type.DATA}} 

请及时准备，避免错过安排。 
点击查看详情


[ 2016-03-19 ] : 与腾讯确认自定义模板过程中，经申请，必须要有通用性，因此更改为:
节日提醒
{{first.DATA}}
节日名称：{{keyword1.DATA}}
节日日期：{{keyword2.DATA}}
节日类型：{{keyword3.DATA}}
{{remark.DATA}}

[2016-3-22] : 腾讯2次驳回自定义模板，原因是: 节日不允许、计划性质不允许。避免过多打扰.. 所以用如下模板吧:
{{first.DATA}}
待办事项：{{keyword1.DATA}}
优先级：{{keyword2.DATA}}
{{remark.DATA}}
		 */
		
		$success="";
		// 遍历每一个节日，对用户发消息
		foreach($fetv as $key=>$value) {
			$remind = M ( 'calendar_remind_info' )->where (Array('id'=>$value)) ->find();
			$url = U('edit?id=' . $value . "&publicid=" . get_token_appinfo( '', 'id'));
			$template_id = 'K8fw4OhR2x_HFKT9TjPaUajl4gYTpKgRyF9bFjnBg-0';
			
			$date = $remind['remind_year'] . "-" . $remind['remind_month'] . "-" . $remind['remind_day'];
			
			$day_string = $remind['remind_set']==0 ? "今天" : $remind['remind_set'] . " 天后";
			
			$param['data'] = Array(
				'first' => Array('value'=>"你好，" . $day_string . " 有一个待办事项/节日来临" . "\\n", 'color'=>'#000000'),
				'keyword1' => Array('value'=>$remind['remind_title'], 'color'=> '#0000FF'),	// 名称
				'keyword2' => Array('value'=>"　默认" . "\\n事项日期：" . $date, 'color'=>'#000000'),
				'remark' => Array('value'=>'\\n请及时准备，避免错过安排。 \\n点击查看详情' , 'color'=>'#000000')
			);
			
			$res = $this->_replyData($remind['uid'], $param, $template_id, $url);
			if($res['status'] == 1) {
				$success .= $remind['remind_title'] . ",";
			} else {
				$error .= $remind['remind_title'] . ", error msg is: " . $res['msg'] . "\n";
			}
		}
		
		$this->display('','','', ("success: " . $success . "**** error is: " . $error . " -- send_template_remind  -end"));
	}
	
	
	//显示古曼图日历主页
	public function show() {
		$this->display();
	}
	
	// DELETE
	public function delete() {
		$map['uid']=$this->mid;
		$map['id'] = $_REQUEST['id'];
		
		if (M('calendar_remind_info')->where($map)->delete()) {
			$this->success ( '删除成功！');
		}
		else {
			$this->error ('删除失败，请重试！');
		}
	}
	
	// 显示用户的纪念日
	public function lists() {
		$map['uid']=$uid=$this->mid;
		
		if(isset($_REQUEST['recycle'])) {
			$map['recycle'] = $_REQUEST['recycle'];
			
			switch($_REQUEST['recycle']) {
				case '1': $this->assign ( 'yearClass', 'current' ); break;
				case '2': $this->assign ( 'monthClass', 'current' ); break;
				case '3': $this->assign ( 'onceClass', 'current' ); break;
				default:
					break;
			}
		}
		else {
			$this->assign ( 'allClass', 'current' );
		}
		
		$data=M('calendar_remind_info')->where($map) -> order('ctime desc') ->select();
		$this->assign ( 'fetv_list', $data );
		
		$this->display();
	}
	
	// 执行纪念日添加 
	public function edit() {
		$act='edit';
		$data = null;
		$model = $this->getModel ( 'calendar_remind_info' );
	    
		if(isset($_REQUEST['id'])) {
			$map['uid']=$uid=$this->mid;
			$map['id'] = $_POST['id']= $_REQUEST['id'];
			$data=M('calendar_remind_info')->where($map)->find();
		}
		
		$data || $act='add';
		
		file_put_contents("./csz3.txt", "data=" . serialize($data) . ", \n_REQUEST=" . serialize($_REQUEST) . "\n", FILE_APPEND);
	    
	    if (IS_POST) {
	        $_POST['uid']=$this->mid;
	        $_POST['token']=get_token();
			$_POST['ctime']=time();
			
	        $Model = D ( parse_name ( get_table_name ( $model ['id'] ), 1 ) );
	        // 获取模型的字段信息
	        $Model = $this->checkAttr ( $Model, $model ['id'] );
			
	        if ($act=='edit'){
	            if ($Model->create () && $Model->save ()) {
	                // 清空缓存
	                method_exists ( $Model, 'clear' ) ;
					
					// 新增成功则跳转到lists页面
	                $this->success ( '保存&nbsp"' . $_POST['remind_title'] . '"&nbsp;成功！', U('lists'));
	            } else {			
					$error = $Model->getError ();
					if("操作出现错误" == $error) {
						$error = "保存&nbsp;\"" . $_POST['remind_title'] . "\"&nbsp; 失败";
					}
					
					$this->error ($error);
	            }
	        }else {
				// title must be unique when add new
				$map2['uid']=$uid=$this->mid;
				$map2['remind_title'] = $_POST['remind_title'];
				$data=M('calendar_remind_info')->where($map2)->find();
				
				if(!empty($data) || $_POST['remind_title']=="") {
					$error = "保存失败，名称为空或者已经有一个名称为&nbsp;" . $_POST['remind_title'] . "&nbsp;的纪念日了";
					
					$this->error ($error);
					return;
				}
				
	            if ($Model->create () && $id = $Model->add ()) {
	                 
	                // 清空缓存
	                method_exists ( $Model, 'clear' ) && $Model->clear ( $id, 'add' );
	                 
	                $this->success ( '保存&nbsp"' . $_POST['remind_title'] . '"&nbsp;成功！', U('lists'));
	            } else {
					$error = $Model->getError ();
					if("操作出现错误" == $error) {
						$error = "保存&nbsp;" . $_POST['remind_title'] . "&nbsp;纪念日 失败";
					}
					
					$this->error ($error);
				}
	        }
	       
	    } else {
	        $fields = get_model_attribute ( $model ['id'] );
			
			if(empty($data)) {
				// 初始化显示
				$data = Array(
					'remind_year' => date('Y'),
					'remind_month' => date('n'),
					'remind_day' => date('j'),
					'date_format' => '0',
					'recycle' => '1',
					'remind_set' => '-1',		// 默认不提醒
					'remind_set_time' => '9'	// 默认9点
				);
			}
			if(empty($data['remind_year']))
				$data['remind_year'] = date('Y');
			
			if(empty($data['remind_month']))
				$data['remind_month'] = date('n');
			// 日期一定有设置
	
	
			$this->assign ( 'vo', $data );
	        $this->display ();
	    }
		
	}
	
	
	public function get_fetv() {
		$_POST['uid'] = $this->mid;
		$fetv = $this->_get_fetv($_POST);
		
		$id=Array(); 
		$remind_title=Array();
		foreach($fetv as $key => $value) {
			$remind_title = empty($remind_title) ? Array(urlencode($key)) : array_merge($remind_title, Array(urlencode($key)));
			$id = empty($id) ? Array(urlencode($value)) : array_merge($id, Array(urlencode($value)));
		}
		$out = empty($id) ? '' : Array('remind_title'=>$remind_title, 'id'=>$id);
		
		$this->display('','','', urldecode(json_encode($out)));

	}
}
